// self header files

// c or cpp standard header files
#include <stdio.h>
#include <assert.h>

// system header files
#include <unistd.h>
#include <pthread.h>

#define LOCK(q) while (__sync_lock_test_and_set(&q, 1)) {}
#define UNLOCK(q) __sync_lock_release(&q);

int lock;
int count;

void* thread1(void* para) {
	usleep(1000 * 20);
	int i, j = 1;

	LOCK(lock)
	for (i = 0; i < 1000; ++i) {
		count = count + j;
	}
	UNLOCK(lock)

	return 0;
}

int main(void) {
#define thrd_num 16
	pthread_t threads[thrd_num];

	int rc, i;
	for (i = 0; i < thrd_num; ++i) {
		rc = pthread_create(&threads[i], NULL, thread1, NULL);
		assert(rc == 0);
	}

	for (i = 0; i < thrd_num; ++i) {
		pthread_join(threads[i], NULL);
		printf("thread[%d] return\n", i);
	}
	
	printf("cout : %d\n", count);
	return 0;
}
